//
//  ViewController.m
//  GaoMapDemo
//
//  Created by wayfor on 17/3/6.
//  Copyright © 2017年 wayfor. All rights reserved.
//

#import "ViewController.h"

#import "MANaviRoute.h"

#import "CustomAnnotationView.h"

#import "CommonUtility.h"

#import "MapTopView.h"

#import "LocationModel.h"

//#import <MAMapKit/MAAnnotation.h>

#define kCalloutViewMargin          -8

static const NSInteger RoutePlanningPaddingEdge                    = 20;

@interface ViewController ()<MAMapViewDelegate,AMapLocationManagerDelegate,AMapSearchDelegate>
{
    UIImageView *oldImageView;
    CLLocationCoordinate2D stopCoordinate;
//    CLLocationCoordinate2D beginCoordinate;

    MapTopView *topView;
    double distance;
    NSString *locationAddress;
    
    BOOL isFirstGuiHua;
    CLLocationCoordinate2D centerCoordinate;//上一次起始点坐标
    MAPointAnnotation* centerPointAnnotation;
}

@property (nonatomic, strong) UIButton *refreshBtn;
@property (nonatomic) BOOL refreshBtnActive;

//MAAnnotationView
@property (nonatomic, strong) MAAnnotationView *userLocationAnnotationView;


@property (nonatomic, strong) MAMapView *mapView;
@property (nonatomic, strong) AMapLocationManager *locationManager;
@property (nonatomic) CLLocationCoordinate2D *coor;
@property (nonatomic, strong) CLLocation *location;
@property (nonatomic, strong) MAPointAnnotation *currentAnnotation;

@property (nonatomic, strong) AMapRoute *route;
@property (nonatomic, strong) AMapSearchAPI *search;

/* 当前路线方案索引值. */
@property (nonatomic) NSInteger currentCourse;
/* 路线方案个数. */
@property (nonatomic) NSInteger totalCourse;

/* 起始点经纬度. */
@property (nonatomic) CLLocationCoordinate2D startCoordinate;
/* 终点经纬度. */
@property (nonatomic) CLLocationCoordinate2D destinationCoordinate;

/*上一次起始点坐标*/
//@property (nonatomic) CLLocationCoordinate2D centerCoordinate;

/* 用于显示当前路线方案. */
@property (nonatomic) MANaviRoute * naviRoute;

@property (nonatomic, strong) MAPointAnnotation *startAnnotation;
@property (nonatomic, strong) MAPointAnnotation *destinationAnnotation;


@property (nonatomic, strong) NSMutableArray *annotationsMuArray;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    ///初始化地图
    _mapView = [[MAMapView alloc] init];
    _mapView.delegate = self;
    
    self.mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    //如果您需要进入地图就显示定位小蓝点，则需要下面两行代码
    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = MAUserTrackingModeFollow;
    //_mapView.mapType = MAMapTypeNavi;
    _mapView.customizeUserLocationAccuracyCircleRepresentation = NO;
//    _mapView.showsCompass = NO;
    //    [_mapView setCompassImage:[UIImage imageNamed:@"compass"]];
    _mapView.showsScale = NO;
    _mapView.showsBuildings = YES;
    _mapView.rotateEnabled = YES;
    _mapView.zoomLevel = 17.2;

    /*----长按增加大头针-----
     --- //坐标转换
     CGPoint touchPoint = [gestureRecognizer locationInView:_mapView];
     CLLocationCoordinate2D touchMapCoordinate =
     [_mapView convertPoint:touchPoint toCoordinateFromView:_mapView];
     
     MKPointAnnotation* pointAnnotation = nil;
     pointAnnotation = [[MKPointAnnotation alloc] init];
     pointAnnotation.coordinate = touchMapCoordinate;
     pointAnnotation.title = @"设置名字";
     
     [_mapView addAnnotation:pointAnnotation];
     -------*/
    
//    [_mapView setUserTrackingMode:MAUserTrackingModeFollow animated:<#(BOOL)#>];
    //    _mapView
    ///把地图添加至view
    [self.view addSubview:_mapView];
    
    [_mapView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];

    
     //拿出xib视图
    topView = [MapTopView instanceDatePickerView];
    [self.view addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).with.offset(0);
        make.right.equalTo(self.view).with.offset(0);
        make.top.equalTo(self.view).with.offset(64);
        make.height.equalTo(@(150));
    }];
    topView.alpha = 0;
    

    //自定义大头针
    isFirstGuiHua = YES;
    oldImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 18, 25)];
    
//    oldImageView.center = _mapView.center;
    
    oldImageView.image = [UIImage imageNamed:@"box-location"];  //添加大头针,使它固定在屏幕中心
    
    [_mapView addSubview:oldImageView];

    //logo位置
    CGFloat logoCenterX = self.mapView.logoCenter.x;
    CGPoint oldCenter = self.mapView.logoCenter;
    _mapView.logoCenter = CGPointMake(CGRectGetWidth(self.view.bounds) - logoCenterX, oldCenter.y);

    [self configLocationManager];
    [self startSerialLocation];
    
    
    UIButton *userLocaBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [userLocaBtn setImage:[UIImage imageNamed:@"user-local-btn"] forState:UIControlStateNormal];
    [self.view addSubview:userLocaBtn];
    [userLocaBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).with.offset(-45);
        make.left.equalTo(self.view).with.offset(12);
    }];
    
    [userLocaBtn addTarget:self action:@selector(locationToUser) forControlEvents:UIControlEventTouchUpInside];

    
    UIButton *refreshLocalBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _refreshBtn = refreshLocalBtn;
    _refreshBtnActive = NO;
    [refreshLocalBtn setImage:[UIImage imageNamed:@"refresh-local-btn"] forState:UIControlStateNormal];
    [self.view addSubview:refreshLocalBtn];
    [refreshLocalBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(userLocaBtn);
        make.bottom.equalTo(userLocaBtn.mas_top).with.offset(-16);
    }];
    [refreshLocalBtn addTarget:self action:@selector(refreshData:) forControlEvents:UIControlEventTouchUpInside];

    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;

    
//    self.startAnnotation.coordinate = self.startCoordinate;
//    self.destinationAnnotation.coordinate = self.destinationCoordinate;
//    
//    AMapWalkingRouteSearchRequest *navi = [[AMapWalkingRouteSearchRequest alloc] init];
//    
//    /* 出发点. */
//    navi.origin = [AMapGeoPoint locationWithLatitude:self.startCoordinate.latitude
//                                           longitude:self.startCoordinate.longitude];
//    /* 目的地. */
//    navi.destination = [AMapGeoPoint locationWithLatitude:self.destinationCoordinate.latitude
//                                                longitude:self.destinationCoordinate.longitude];
//    
//    [self.search AMapWalkingRouteSearch:navi];

}

- (void)refreshData:(UIButton *)sender{
    
    
    [self.mapView removeAnnotations:self.annotationsMuArray];
    [self.annotationsMuArray removeAllObjects];

//    self.annotationsMuArray = [NSMutableArray array];
    if (!_refreshBtnActive) {
        [self startRefresh];
    }

    [self initAnnotations];
    _mapView.zoomLevel = 17.2;
    [_mapView setCenterCoordinate:_location.coordinate];
    [_mapView reloadMap];

    //规划信息
    topView.alpha = 0.f;
    [UIView animateWithDuration:0.5f animations:^{
        topView.top = -150-64;
    }];

//    [self loadData];
}

- (void)startRefresh{
    _refreshBtnActive = YES;
    
    
    oldImageView.hidden = NO;
    isFirstGuiHua = YES;

    [self clear];
    
    NSLog(@"center%f",centerCoordinate.latitude);
    [_mapView removeAnnotation:centerPointAnnotation];

    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    animation.toValue = [NSNumber numberWithInt:0.f];
    animation.fromValue = [NSNumber numberWithInt:M_PI * 2];
    animation.duration = 1.0;
    animation.repeatCount = 100;
    animation.fillMode = kCAFillModeRemoved;
    [_refreshBtn.layer addAnimation:animation forKey:@"transform-layer"];
}


- (void)stopRefresh{
    if (_refreshBtnActive) {
        _refreshBtnActive = NO;
        [_refreshBtn.layer removeAnimationForKey:@"transform-layer"];
        _refreshBtn.hidden = YES;
        _refreshBtn.alpha = 0.0;
        

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:0.3 animations:^{
                _refreshBtn.hidden = NO;
                _refreshBtn.alpha = 1.0;
                

            }];
        });
        

    }
}


//设置当前地图的中心点
- (void)locationToUser{
    
    oldImageView.hidden = NO;
    isFirstGuiHua = YES;
    
    [self clear];
    
    NSLog(@"center%f",centerCoordinate.latitude);
    [_mapView removeAnnotation:centerPointAnnotation];

    //规划信息
    topView.alpha = 0.f;
    [UIView animateWithDuration:0.5f animations:^{
        topView.top = -150-64;
    }];
    
    [_mapView setCenterCoordinate:_mapView.userLocation.coordinate animated:YES];
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    self.tabBarController.tabBar.alpha = 0.0;
    

}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
//    [self.mapView addAnnotations:self.annotationsMuArray];
    
    if (_location != nil) {
        CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(_location.coordinate.latitude, _location.coordinate.longitude);
        [self.mapView setCenterCoordinate:coordinate animated:YES];
        _location = nil;
    }
    else{
        [_mapView setCenterCoordinate:_mapView.userLocation.coordinate animated:YES];                                                                                                                                                       
    }

}

- (void)configLocationManager
{
    self.locationManager = [[AMapLocationManager alloc] init];
    //定位精度
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    self.locationManager.locationTimeout = 2;
    self.locationManager.reGeocodeTimeout = 2;
    [self.locationManager setDelegate:self];
    
    
//        [self.locationManager setPausesLocationUpdatesAutomatically:NO];
    //
//        [self.locationManager setAllowsBackgroundLocationUpdates:YES];
}

- (void)startSerialLocation
{
    //开始定位
    [self.locationManager startUpdatingLocation];
}

- (void)stopSerialLocation
{
    //停止定位
    [self.locationManager stopUpdatingLocation];
}

#pragma makr -AMapLocationManagerDelegate
/**
 *  当定位发生错误时，会调用代理的此方法。
 *
 *  @param manager 定位 AMapLocationManager 类。
 *  @param error 返回的错误，参考 CLError 。
 */

-(void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error
{
    //定位错误
    NSLog(@"%s, amapLocationManager = %@, error = %@", __func__, [manager class], error);
}

-(void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location
{
    //定位结果
    NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
//    [self stopSerialLocation];

    [_mapView setCenterCoordinate:location.coordinate];

//    [_mapView convertCoordinate:location.coordinate toPointToView:_mapView];

    _userLocation = location;
    if (!_location) {
        //[_mapView reloadMap];
        
        [self stopSerialLocation];
        [_mapView setCenterCoordinate:_location.coordinate];

        _location = location;
        NSLog(@"定位坐标：%f，%f-开始加载数据", _location.coordinate.latitude, _location.coordinate.longitude);

//        MAPointAnnotation* pointAnnotation = nil;
//        pointAnnotation = [[MAPointAnnotation alloc] init];
//        pointAnnotation.coordinate = _location.coordinate;
//        pointAnnotation.lockedToScreen = YES;
//        pointAnnotation.lockedScreenPoint = _mapView.center;
////        pointAnnotation.title = @"设置名字";
//        [_mapView addAnnotation:pointAnnotation];

        
//        [self locateAction];
//        //逆地理编码
//        [self regecodeWay];
        [self regecodeWay:_location.coordinate.latitude longitude:_location.coordinate.longitude];

        //固定点
        oldImageView.center = CGPointMake(_mapView.center.x, _mapView.center.y-12);

        [self initAnnotations];
        
        [self startRefresh];
        
//        [self loadData];
    }
    _location = location;

}

- (CGPoint)randomPoint
{
    
    //22.541703，114.114095
    CGPoint randomPoint = CGPointZero;
    
//    randomPoint.x = arc4random() % (int)(CGRectGetWidth(self.view.bounds));
    randomPoint.x = _location.coordinate.latitude;
//    randomPoint.y = arc4random() % (int)(CGRectGetHeight(self.view.bounds));
    randomPoint.y = _location.coordinate.longitude+0.019999;

//    NSLog(@"%.2f,%2.f",randomPoint.x,randomPoint.y);
    return randomPoint;
}


- (void)initAnnotations {
    self.annotationsMuArray = [NSMutableArray array];
    
    CGFloat jingDu = _location.coordinate.latitude;
    CGFloat weiDu = _location.coordinate.longitude;
//
//    
//    CLLocationCoordinate2D coordinates = {jingDu, weiDu};
    
//    MAPointAnnotation *a = [[MAPointAnnotation alloc] init];
//    a.coordinate = coordinates;
//    a.lockedToScreen = YES;
//    
//    a.lockedScreenPoint = _mapView.center;
//    [self.annotationsMuArray addObject:a];
//    [self.mapView addAnnotation:a];

    
    
    CLLocationCoordinate2D coordinatesNew1 = {jingDu, (weiDu+0.001)};
    CLLocationCoordinate2D coordinatesNew2 = {jingDu, (weiDu+0.0012)};
    CLLocationCoordinate2D coordinatesNew3 = {(jingDu+0.001), (weiDu+0.002)};
    CLLocationCoordinate2D coordinatesNew4 = {(jingDu+0.001), (weiDu+0.001)};
//    NSLog(@"%.5f,%.5f",coordinatesNew1.latitude,coordinatesNew1.longitude);
    
//    CGFloat distance = MAMetersBetweenMapPoints(MAMapPointForCoordinate(_location.coordinate), MAMapPointForCoordinate(coordinatesNew1));
//    
//    if(50 <= distance <= 400.0){
//    }

    for (int i = 1; i <= 4; i++) {
//        CLLocationCoordinate2D randomCoordinate = [self.mapView convertPoint:[self randomPoint] toCoordinateFromView:self.view];
        CLLocationCoordinate2D randomCoordinate;
        switch (i) {
            case 1:
                randomCoordinate = coordinatesNew1;
                break;
            case 2:
                randomCoordinate = coordinatesNew2;
                break;
            case 3:
                randomCoordinate = coordinatesNew3;
                break;
            case 4:
                randomCoordinate = coordinatesNew4;
                break;
                
            default:
                break;
        }
        
        [self addAnnotationWithCooordinate:randomCoordinate];


    }


    
//    for (int i = 0; i < 2; ++i)
//    {
//        
//        if(i == 0) {
//            a.lockedToScreen = YES;
//            a.lockedScreenPoint = CGPointMake(100, 100);
//        }
//    }
//    [self stopRefresh];
    [self performSelector:@selector(stopRefresh) withObject:nil afterDelay:0.5];
    [self.mapView addAnnotations:self.annotationsMuArray];

//    [self refreshData:nil];

}

#pragma mark - Utility

-(void)addAnnotationWithCooordinate:(CLLocationCoordinate2D)coordinate
{
    MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
    annotation.coordinate = coordinate;
    annotation.title    = @"AutoNavi";
    annotation.subtitle = @"CustomAnnotationView";
    [self.annotationsMuArray addObject:annotation];

    //[self.mapView addAnnotation:annotation];
}

- (void)locateAction
{
    //带逆地理的单次定位
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        
        if (error)
        {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            
            if (error.code == AMapLocationErrorLocateFailed)
            {
                return;
            }
        }
        
        //定位信息
        NSLog(@"location:%@", location);
        
        //逆地理信息
        if (regeocode)
        {
            NSLog(@"reGeocode:%@", regeocode);
        }
    }];
}

- (void)regecodeWay:(CGFloat)latitudes longitude:(CGFloat)longitudes
{
    //如果将坐标转为地址,需要进行逆地理编码
    
    //设置逆地理编码查询参数 ,进行逆地编码时，请求参数类为 AMapReGeocodeSearchRequest，location为必设参数。
    
    AMapReGeocodeSearchRequest *_regeo = [[AMapReGeocodeSearchRequest alloc] init];
    
    _regeo.location = [AMapGeoPoint locationWithLatitude:latitudes longitude:longitudes];
    
    _regeo.requireExtension = YES;
    
    [_search AMapReGoecodeSearch:_regeo];
    
}

/**
 *  逆地理编码查询回调函数
 *
 *  @param request  发起的请求，具体字段参考 AMapReGeocodeSearchRequest 。
 *  @param response 响应结果，具体字段参考 AMapReGeocodeSearchResponse 。
 */

-(void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    if (response.regeocode != nil)
    {
        NSLog(@"逆地理编码结果：%@", response.regeocode.formattedAddress);
        
        locationAddress = response.regeocode.formattedAddress;
        locationAddress = [locationAddress substringFromIndex:6];
    }

    
}

- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
//    if (updatingLocation)
//    {
//        NSLog(@"userlocation :%@", userLocation.location);
//    }
//    
    
    // 让定位箭头随着方向旋转
    if (!updatingLocation || self.userLocationAnnotationView != nil)
    {
        
        [UIView animateWithDuration:0.1 animations:^{
            
            double degree = userLocation.heading.trueHeading - self.mapView.rotationDegree;
            self.userLocationAnnotationView.transform = CGAffineTransformMakeRotation(degree * M_PI / 180.f);
        }];
    }
}


/* 路径规划搜索回调. */
- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response
{
    if (response.route == nil)
    {
        return;
    }
    
    self.route = response.route;
//    [self updateTotal];
    self.currentCourse = 0;
    
    AMapGeoPoint *star = self.route.origin;
    AMapGeoPoint *stop = self.route.destination;


    AMapWalking *path = (AMapWalking *)self.route.paths[0];
    NSLog(@"距离-%ld",path.distance);
    NSLog(@"秒-%ld",path.duration);
    AMapStep *step = path.steps[0];
    NSLog(@"-%@",step.instruction);

    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:[NSString stringWithFormat:@"%ld",path.distance] forKey:@"LocationDistance"];
    [dic setObject:[NSString stringWithFormat:@"%ld",path.duration] forKey:@"LocationTime"];
    
    [dic setObject:[NSString stringWithFormat:@"%f",stop.latitude] forKey:@"LocationLatitude"];
    [dic setObject:[NSString stringWithFormat:@"%f",stop.longitude] forKey:@"LocationLatitude"];

    //LocationAddress
    if (locationAddress.length > 0) {
        [dic setObject:locationAddress forKey:@"LocationAddress"];
    }
    LocationModel *loModel = [[LocationModel alloc] initContentWithDic:dic];
    NSLog(@"秒-%@",loModel.LocationTime);
    topView.model = loModel;
    
//    [self updateCourseUI];
//    [self updateDetailUI];
    
    if (response.count > 0)
    {
        [self presentCurrentCourse:star destinstion:stop];
        
        //
    }
}


/* 展示当前路线方案. */
- (void)presentCurrentCourse:(AMapGeoPoint *)star destinstion:(AMapGeoPoint *)stop
{

//    CLLocationCoordinate2D img2D = CLLocationCoordinate2DMake(star.latitude, star.longitude);
//    CGPoint imgPoint =
//    [_mapView convertCoordinate:img2D toPointToView:_mapView];
//
//    oldImageView.center = CGPointMake(imgPoint.x,imgPoint.y);

    self.startCoordinate = CLLocationCoordinate2DMake(star.latitude, star.longitude);
    self.destinationCoordinate = CLLocationCoordinate2DMake(stop.latitude, stop.longitude);
    
    //NSLog(@"%.3f,%.3f",self.destinationCoordinate.latitude,self.destinationCoordinate.longitude);

    self.startAnnotation.coordinate = self.startCoordinate;
    self.destinationAnnotation.coordinate = self.destinationCoordinate;
    MANaviAnnotationType type = MANaviAnnotationTypeWalking;
    
//    NSLog(@"%.3f,%.3f",self.destinationAnnotation.coordinate.latitude,self.destinationAnnotation.coordinate.longitude);
    self.naviRoute = [MANaviRoute naviRouteForPath:self.route.paths[self.currentCourse] withNaviType:type showTraffic:YES startPoint:[AMapGeoPoint locationWithLatitude:self.startCoordinate.latitude longitude:self.startCoordinate.longitude] endPoint:[AMapGeoPoint locationWithLatitude:self.destinationCoordinate.latitude longitude:self.destinationCoordinate.longitude]];
    [self.naviRoute addToMapView:self.mapView];
    
    /* 缩放地图使其适应polylines的展示. */
    [self.mapView setVisibleMapRect:[CommonUtility mapRectForOverlays:self.naviRoute.routePolylines]
                        edgePadding:UIEdgeInsetsMake(RoutePlanningPaddingEdge, RoutePlanningPaddingEdge, RoutePlanningPaddingEdge, RoutePlanningPaddingEdge)
                           animated:YES];
}

/* 清空地图上已有的路线. */
- (void)clear
{
    [self.naviRoute removeFromMapView];
}

- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"Error: %@", error);
}
/**
 * @brief 当取消选中一个annotation views时，调用此接口
 * @param mapView 地图View
 * @param view 取消选中的annotation views
 */

-(void)mapView:(MAMapView *)mapView didDeselectAnnotationView:(MAAnnotationView *)view
{
    
}

/**
 * @brief 地图区域改变完成后会调用此接口
 * @param mapView 地图View
 * @param animated 是否动画
 */
-(void)mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    NSLog(@"地图中心点经度：%f",mapView.region.center.latitude); //拿到中心点的经纬度
    NSLog(@"纬度：%f\n",mapView.region.center.longitude);
    NSLog(@"--选择点%.3f", stopCoordinate.latitude);

    CLLocationCoordinate2D beginCoordinate = {mapView.region.center.latitude,mapView.region.center.longitude};
    
    if (stopCoordinate.latitude > 0) {
        //选择点
//        [self searchRoutePlanningWalk:beginCoordinate destination:stopCoordinate];

    }
}

/**
 * @brief 当选中一个annotation views时，调用此接口
 * @param mapView 地图View
 * @param view 选中的annotation views
 */

-(void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view
{
    

    MAUserLocation *location = view.annotation;
    
    NSString *string = location.title;
    NSLog(@"%@",string);
    if ([string isEqualToString:@"当前位置"] || [string isEqualToString:@"first"]) {
        //
        view.canShowCallout = NO;
    }else{
    
        if (isFirstGuiHua) {
            CGPoint centerPoint = _mapView.center;//这里touchPoint是点击的某点在地图控件中的位置
            CLLocationCoordinate2D centerMapCoordinate =
            [_mapView convertPoint:centerPoint toCoordinateFromView:_mapView];
            centerCoordinate = centerMapCoordinate;

            isFirstGuiHua = NO;
            
            oldImageView.hidden = YES;
            
//            MAPointAnnotation* pointAnnotation = nil;
            centerPointAnnotation = [[MAPointAnnotation alloc] init];
            centerPointAnnotation.coordinate = centerCoordinate;
            centerPointAnnotation.title = @"始点";
            [_mapView addAnnotation:centerPointAnnotation];

            //规划信息
            topView.alpha = 1.f;
            [UIView animateWithDuration:0.5f animations:^{
                topView.top = 64;
            }];

        }
        CGPoint touchPoint = view.center;//这里touchPoint是点击的某点在地图控件中的位置
        CLLocationCoordinate2D touchMapCoordinate =
        [_mapView convertPoint:touchPoint toCoordinateFromView:_mapView];//这里touchMapCoordinate就是该点的经纬度了
        
        
//        MAPointAnnotation* pointAnnotationDelete = nil;
//        pointAnnotationDelete = [[MAPointAnnotation alloc] init];
//        pointAnnotationDelete.coordinate = _location.coordinate;
//        pointAnnotationDelete.lockedToScreen = NO;
//        [_mapView removeAnnotation:pointAnnotationDelete];
        

        //逆地理编码
        [self regecodeWay:touchMapCoordinate.latitude longitude:touchMapCoordinate.longitude];

//        NSLog(@"%.3f,%.3f",touchMapCoordinate.latitude,touchMapCoordinate.longitude);

        CLLocationCoordinate2D randomCoordinate = [_mapView convertPoint:_mapView.center toCoordinateFromView:_mapView];
        
        self.startCoordinate        = centerCoordinate;
//        self.startCoordinate        = _location.coordinate;

//        CGFloat jingDu = _location.coordinate.latitude;
//        CGFloat weiDu = _location.coordinate.longitude;
        
//        NSLog(@"view-%.3f", self.startCoordinate.latitude);
        
//        CLLocationCoordinate2D coordinatesNew1 = {jingDu, (weiDu+0.001)};
        //self.startCoordinate = coordinatesNew2;
        
        self.destinationCoordinate  = touchMapCoordinate;
        stopCoordinate = touchMapCoordinate;
        NSLog(@"star--%.3f,%.3f", randomCoordinate.latitude,randomCoordinate.longitude);
//        [self searchRoutePlanningWalk:randomCoordinate destination:stopCoordinate];

        [self searchRoutePlanningWalk:_location.coordinate destination:touchMapCoordinate];
        [self clear];

    }
    

//    [self startCoordinate];
    
    
}

#pragma mark - do search
- (void)searchRoutePlanningWalk:(CLLocationCoordinate2D)start destination:(CLLocationCoordinate2D)destination
{
    self.startAnnotation.coordinate = start;
    self.destinationAnnotation.coordinate = destination;
    
    NSLog(@"%.3f,%.3f",destination.latitude,destination.longitude);

    
    AMapWalkingRouteSearchRequest *navi = [[AMapWalkingRouteSearchRequest alloc] init];
    
    /* 提供备选方案*/
    navi.multipath = 1;
    /* 出发点. */
    navi.origin = [AMapGeoPoint locationWithLatitude:self.startCoordinate.latitude
                                           longitude:self.startCoordinate.longitude];
    /* 目的地. */
    navi.destination = [AMapGeoPoint locationWithLatitude:self.destinationCoordinate.latitude
                                                longitude:self.destinationCoordinate.longitude];
    
    [self.search AMapWalkingRouteSearch:navi];
}



/**
 * @brief 根据anntation生成对应的View
 * @param mapView 地图View
 * @param annotation 指定的标注
 * @return 生成的标注View
 */

-(MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        
//        if (annotation == self.annotationsMuArray.firstObject) {
//            
//            static NSString *pointReuseIdentifier = @"pointReuseIdentifier";
//            MAPinAnnotationView *annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIdentifier];
//
//            if (annotationView == nil)
//            {
//                annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIdentifier];
//                
//                annotationView.canShowCallout            = NO;
//                annotationView.animatesDrop              = NO;
//                annotationView.draggable                 = YES;
//                
//                //设置中心点偏移，使得标注底部中间点成为经纬度对应点
//                annotationView.centerOffset = CGPointMake(0, -18);
//
//            }
//            
//            //        annotationView.pinColor = (annotation == self.annotations.firstObject ? MAPinAnnotationColorRed : MAPinAnnotationColorGreen);
//            annotationView.pinColor = MAPinAnnotationColorRed;
//            return annotationView;
//
//        }else
        if ([annotation isKindOfClass:[MANaviAnnotation class]])
        {
            
            static NSString *routePlanningCellIdentifier = @"RoutePlanningCellIdentifier";
            
            MAAnnotationView *poiAnnotationView = (MAAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:routePlanningCellIdentifier];
            if (poiAnnotationView == nil)
            {
                poiAnnotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation
                                                                 reuseIdentifier:routePlanningCellIdentifier];
            }
            
            
            poiAnnotationView.canShowCallout = YES;
            poiAnnotationView.image = nil;

            switch (((MANaviAnnotation*)annotation).type)
            {
                case MANaviAnnotationTypeRailway:
                    poiAnnotationView.image = [UIImage imageNamed:@"railway_station"];
                    break;
                    
                case MANaviAnnotationTypeBus:
                    poiAnnotationView.image = [UIImage imageNamed:@"bus"];
                    break;
                    
                case MANaviAnnotationTypeDrive:
                    poiAnnotationView.image = [UIImage imageNamed:@"car"];
                    break;
                    
                case MANaviAnnotationTypeWalking:
                    poiAnnotationView.image = [UIImage imageNamed:@"man"];
                    break;
                    
                default:
                    break;
            }
            
            return poiAnnotationView;

        }else{
        
            static NSString *customReuseIndetifier = @"customReuseIndetifier";
            
            CustomAnnotationView *annotationView = (CustomAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndetifier];
            
            if (annotationView == nil)
            {
                annotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:customReuseIndetifier];
                // must set to NO, so we can show the custom callout view.
                annotationView.canShowCallout = NO;
                annotationView.draggable = YES;
//                annotationView.animatesDrop = YES;
                annotationView.calloutOffset = CGPointMake(0, -10);
            }
            
                if ([annotation.title isEqualToString:@"始点"]) {
                    annotationView.portrait = [UIImage imageNamed:@"box-location"];
                    annotationView.enabled = NO;
//                    annotationView.name = @"first";
//                    annotationView.first = 1;
                    //设置中心点偏移，使得标注底部中间点成为经纬度对应点
                    annotationView.centerOffset = CGPointMake(0, -8);
                }else{
                    annotationView.portrait = [UIImage imageNamed:@"anjuke_icon_itis_position"];
//                    annotationView.first = 0;

//                    annotationView.name     = @"heheh";

                }
            
            return annotationView;

        }
        

    }else if ([annotation isKindOfClass:[MAUserLocation class]])
    {// 自定义userLocation对应的annotationView
        static NSString *userLocationStyleReuseIndetifier = @"userLocationStyleReuseIndetifier";
        MAAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:userLocationStyleReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation
                                                             reuseIdentifier:userLocationStyleReuseIndetifier];
            annotationView.canShowCallout = NO;
        }
        
        annotationView.image = [UIImage imageNamed:@"box-location"];
        self.userLocationAnnotationView = annotationView;
        return annotationView;
        
    }
    return nil;
}

//大头针显示在视图上时调用，在这里给大头针设置显示动画
-(void)mapView:(MAMapView *)mapView didAddAnnotationViews:(NSArray<CustomAnnotationView *> *)views
{
    //    获得mapView的Frame
    CGRect visibleRect = [mapView annotationVisibleRect];

    for (CustomAnnotationView *view in views) {
        
        if ([view.annotation.title isEqualToString:@"始点"]) {
            
        }else{
            CGRect endFrame = view.frame;
            CGRect startFrame = endFrame;
            startFrame.origin.y = visibleRect.origin.y - startFrame.size.height;
            view.frame = startFrame;
            [UIView beginAnimations:@"drop" context:NULL];
            [UIView setAnimationDuration:0.5];
            view.frame = endFrame;
            [UIView commitAnimations];

        }
        
    }
}

-(MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay
{
//    // 自定义定位精度对应的MACircleView
//    if (overlay == mapView.userLocationAccuracyCircle)
//    {
////        MACircleView *accuracyCircleView = [[MACircleView alloc] initWithCircle:overlay];
////        
////        accuracyCircleView.lineWidth    = 2.f;
////        accuracyCircleView.strokeColor  = [UIColor lightGrayColor];
////        accuracyCircleView.fillColor    = [UIColor colorWithRed:1 green:0 blue:0 alpha:.3];
////        
////        return accuracyCircleView;
//    }else
    if ([overlay isKindOfClass:[LineDashPolyline class]])
    {
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:((LineDashPolyline *)overlay).polyline];
        polylineRenderer.lineWidth   = 5;
        polylineRenderer.lineDash = YES;
        polylineRenderer.strokeColor = [UIColor redColor];
        
        return polylineRenderer;
    }else if ([overlay isKindOfClass:[MANaviPolyline class]])
    {
        MANaviPolyline *naviPolyline = (MANaviPolyline *)overlay;
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:naviPolyline.polyline];
        
        polylineRenderer.lineWidth = 5;
        
        if (naviPolyline.type == MANaviAnnotationTypeWalking)
        {
            polylineRenderer.strokeColor = self.naviRoute.walkingColor;
        }
        else if (naviPolyline.type == MANaviAnnotationTypeRailway)
        {
            polylineRenderer.strokeColor = self.naviRoute.railwayColor;
        }
        else
        {
            polylineRenderer.strokeColor = self.naviRoute.routeColor;
        }
        
        return polylineRenderer;
    }else if ([overlay isKindOfClass:[MAMultiPolyline class]])
    {
        MAMultiColoredPolylineRenderer * polylineRenderer = [[MAMultiColoredPolylineRenderer alloc] initWithMultiPolyline:overlay];
        
        polylineRenderer.lineWidth = 6;
        polylineRenderer.strokeColors = [self.naviRoute.multiPolylineColors copy];
        polylineRenderer.gradient = YES;
        
        return polylineRenderer;
    }
    return nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
